import 'dart:async';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_module/api/entries_view_model.dart';
import 'package:flutter_module/api/news_model.dart';
import 'package:flutter_module/api/news_view_model.dart';
import 'package:flutter_module/api/statistics_view_model.dart';
import 'package:flutter_module/beans/Entity.dart';
import 'package:flutter_module/beans/EntityViewModel.dart';
import 'package:flutter_module/beans/conmmonResult.dart';
import 'package:flutter_module/commom/application.dart';
import 'package:flutter_module/commom/commom.dart';
import 'package:flutter_module/event/getysy_event.dart';
import 'package:flutter_module/event/login_event.dart';
import 'package:flutter_module/event/logout_event.dart';
import 'package:flutter_module/http/api_service.dart';
import 'package:flutter_module/http/dio_manager.dart';
import 'package:flutter_module/widget/card/news_card.dart';
import 'package:oktoast/oktoast.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

// import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:connectivity/connectivity.dart';

import '../../DemoLocalizations.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  bool isReq = false;
  List data = new List();
  App_esp_ip model;
  static const EventChannel eventChannel =
      EventChannel('com.flutter.io/camerasetting');

  String statusText;
  @override
  void initState() {
    super.initState();
    this.registerLoginEvent();
    this.registerLogoutEvent();
    Notice.addListener(NCOVActions.toTabBarIndex(), (index) {
      if (!listNoEmpty(data)) getData();
    });
    changeUI();
    //getWifiStatus();
    eventChannel
        .receiveBroadcastStream()
        .listen(successEvent, onError: onErrorEvent);
  }

  void successEvent(Object event) {
    print('flutter receiveBroadcastStream:' + event.toString());
    //此处仅会收到序列号
    if (event.toString().startsWith("XLH")) {
      String xlh = event.toString().substring(3, event.toString().length);
      print(xlh);
      model.ysyappkey = statusText;
      model.ysyserialnumber = xlh;
      ApiService().ESPEDIT((Response response) {
        if (response != null) {
          ConmmonResult conmmonResult = ConmmonResult.fromJson(response.data);
          if (conmmonResult.success) {
//              print("更新成功！");
            // showToast("更新成功！");
            // Navigator.pop(context);
          } else {
            showToast(conmmonResult.message);
          }
        }
      }, model);

      DioManager.singleton.dio
          .get(API.addYSYNum + statusText, options: null)
          .then((response) {
        print(response.toString());
      });
    }
  }

  void onErrorEvent(Object error) {}

  void registerLoginEvent() {
    Application.eventBus.on<LoginEvent>().listen((event) {
      changeUI();
    });
    Application.eventBus.on<YsyEvent>().listen((event) {
      print(event.str);
      print(event.model);
      model = event.model;
      //ysy帐号
      statusText = event.str;
    });
  }

  void registerLogoutEvent() {
    Application.eventBus.on<LogoutEvent>().listen((event) {
      changeUI();
    });
  }

  changeUI() async {
    entityViewModel.getEntityNews(context).then((v) {
      if (mounted) {
        setState(() {
          data = v;
          isReq = true;
        });
      }
    });
  }

  @override
  bool get wantKeepAlive => true;

  getData() async {
    entityViewModel.getEntityNews(context).then((v) {
      if (mounted) {
        setState(() {
          data = v;
          isReq = true;
        });
      }
    });
  }

  getWifiStatus() async {
    var connectivityResult = await (new Connectivity().checkConnectivity());
    if (connectivityResult == ConnectivityResult.mobile) {
      // I am connected to a mobile network.
    } else if (connectivityResult == ConnectivityResult.wifi) {
      // I am connected to a wifi network.
      var wifiBSSID = await (Connectivity().getWifiBSSID());
      var wifiIP = await (Connectivity().getWifiIP()); //network
      var wifiName = await (Connectivity().getWifiName()); //wifi network
      print(wifiBSSID);
      print(wifiIP);
      print(wifiName);
    }
  }

  Future<void> _refreshData() async {
    final Completer<Null> completer = new Completer<Null>();
    getData();
    new Future.delayed(new Duration(seconds: 1), () {
      completer.complete(null);
      _refreshController.refreshCompleted();
    });

    return completer.future;
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return new Scaffold(
      body: new SmartRefresher(
        controller: _refreshController,
        onRefresh: _refreshData,
        child: isReq
            ? listNoEmpty(data)
                ? new ListView.builder(
                    itemBuilder: (context, index) {
                      App_esp_ip model = data[index];
                      bool isNew = model.id == data[0].id;
                      return new NewsCard(
                        model,
                        padding: EdgeInsets.only(
                          left: 10.0,
                          right: 10.0,
                          top: isNew ? 10.0 : 10,
                          bottom:
                              model.id == data[data.length - 1].id ? 20.0 : 10,
                        ),
                        isNew: isNew,
                      );
                    },
                    itemCount: data.length,
                  )
                : new Center(
                    child: new Text(
                      DemoLocalizations.of(context).NoEquipment,
                      style: Theme.of(context).textTheme.display1,
                    ),
                  )
            : new LoadingView(),
      ),
    );
  }
}
